package com.sc.social.wechet.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author sc
 * Created on  2018/1/18
 */
@Slf4j
public class WechetImpl extends AbstractOAuth2ApiBinding implements Wechet {

    private ObjectMapper objectMapper = new ObjectMapper();

    private final static String URL_GET_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?openid=";

    public WechetImpl(String accessToken){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    @Override
    protected List<HttpMessageConverter<?>> getMessageConverters() {
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
        return messageConverters;
    }

    @Override
    public WechetUserInfo getUserInfo(String openId) {
        String url  = URL_GET_USER_INFO+openId;
        String response = getRestTemplate().getForObject(url,String.class);
        if(StringUtils.contains(response,"errcode")){
            return null;
        }
        WechetUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(response, WechetUserInfo.class);
        } catch (IOException e) {
            log.info("微信用户信息转换出错");
        }
        return userInfo;
    }
}
